package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.CheckPhoneUtil;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.entity.UserAddressEntity;
import com.yuanfeng.userms.mapper.UserAddressMapper;
import com.yuanfeng.userms.service.UserAddressService;
import com.yuanfeng.userms.vo.UserAddressVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName UserAddressServiceImpl
 * @Description  用户地址表
 * @Author cyp
 * @Date 2023-06-16 15:26:50
 * @Version 1.0
 **/
@Service
@Slf4j
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddressEntity>
        implements UserAddressService {

    @Override
    public ResponseResult getDef(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        paraMap.put("userId", userInfo.getUserId());
        UserAddressVO userAddress = this.baseMapper.getDefAddresses(paraMap);
        if (null != userAddress) {
            return ResponseResult.success(userAddress);
        }
        List<UserAddressVO> userAddressList = this.baseMapper.getAddresses(paraMap);
        if (null != userAddressList && 0 != userAddressList.size()) {
            return ResponseResult.success(userAddressList.get(0));
        }
        return ResponseResult.fail(0, "没有地址");
    }

    @Override
    public ResponseResult get(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        if(userInfo == null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        List<UserAddressEntity> userAddressList = this.baseMapper.selectList(new LambdaQueryWrapper<UserAddressEntity>()
                .eq(UserAddressEntity::getUserId,userInfo.getUserId())
                .orderByDesc(UserAddressEntity::getUserAddressDefault,UserAddressEntity::getUserAddressTime)
                );
        if (null != userAddressList) {
            return ResponseResult.success(userAddressList);
        }
        return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED);
    }

    @Override
    public ResponseResult update(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
        paraMap.put("userId", userId);
        String userAddressPhone = paraMap.get("userAddressPhone");
        if (!CheckPhoneUtil.checkPhone(userAddressPhone)) {
            //更新收货地址失败,手机号不正确
            return ResponseResult.fail(BizCodeEnume.FAILED_TO_UPDATE_THE_SHIPPING_ADDRESS.getCode(),
                    BizCodeEnume.FAILED_TO_UPDATE_THE_SHIPPING_ADDRESS.getMsg());
        }
        if ("".equals(paraMap.get("userAddressProvinceId"))) {
            //更新收货地址失败,详细地址为空
            return ResponseResult.fail(BizCodeEnume.DETAILED_ADDRESS_IS_EMPTY.getCode(),
                    BizCodeEnume.DETAILED_ADDRESS_IS_EMPTY.getMsg());
        }

        int userAddressProvinceId = Integer.parseInt(paraMap.get("userAddressProvinceId"));
        if (userAddressProvinceId == 0) {
            //更新收货地址失败,省份不正确
            return ResponseResult.fail(BizCodeEnume.PROVINCE_INCORRECT.getCode(),
                    BizCodeEnume.PROVINCE_INCORRECT.getMsg());
        }
        if (Integer.parseInt(paraMap.get("userAddressDefault")) == 1) {
            //默认地址0不是1是
            this.baseMapper.update(null, new LambdaUpdateWrapper<UserAddressEntity>()
                    .eq(UserAddressEntity::getUserId, userId)
                    .eq(UserAddressEntity::getUserAddressDefault, CommonType.commonStatus.YES.getCode())
                    .set(UserAddressEntity::getUserAddressDefault, CommonType.commonStatus.NO.getCode()));
        }

        Integer torf = this.baseMapper.updateAddress(paraMap);
        if (CommonStatusEnum.SUCCESS.getCode() == torf) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult delete(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
        paraMap.put("userId", userId);
        if(null==paraMap.get("userAddressId")){
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER.getCode(), BizCodeEnume.MISSING_PARAMETER.getMsg());
        }
        Integer torf = this.baseMapper.delete(new LambdaUpdateWrapper<UserAddressEntity>()
                .eq(UserAddressEntity::getUserId, userId)
                .eq(UserAddressEntity::getUserAddressId, paraMap.get("userAddressId")));
        if (CommonStatusEnum.SUCCESS.getCode() == torf) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult add(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        if (userInfoStr == null || "".equals(userInfoStr)) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        UserInfoDTO ui = JSON.parseObject(userInfoStr, UserInfoDTO.class);
        UserInfoVO userInfo = ui.getUser();
        String userId = userInfo.getUserId();
        if ("0".equals(paraMap.get("userAddressProvinceId")) || "0".equals(paraMap.get("userAddressCityId"))
                || "0".equals(paraMap.get("userAddressAreaId")) || "".equals(paraMap.get("userAddressAddress"))) {
            //地址选择失败，请重新选择
            return ResponseResult.fail(BizCodeEnume.ADDRESS_SELECTION_FAILED);
        }
        Integer userAddressDefault = 0;
        if (null != paraMap.get("userAddressDefault") && paraMap.get("userAddressDefault").length() > 0) {
            userAddressDefault = Integer.parseInt(paraMap.get("userAddressDefault"));
        }
        if (CommonType.commonStatus.YES.getCode().equals(userAddressDefault)) {
            //默认地址0不是1是
            this.baseMapper.update(null, new LambdaUpdateWrapper<UserAddressEntity>()
                    .eq(UserAddressEntity::getUserId,userId)
                    .eq(UserAddressEntity::getUserAddressDefault, CommonType.commonStatus.YES.getCode())
                    .set(UserAddressEntity::getUserAddressDefault,CommonType.commonStatus.NO.getCode()));

        }
        String userAddressPhone = paraMap.get("userAddressPhone");
        if (!CheckPhoneUtil.checkPhone(userAddressPhone)) {
            //更新收货地址失败,手机号不正确
            return ResponseResult.fail(BizCodeEnume.FAILED_TO_UPDATE_THE_SHIPPING_ADDRESS);
        }
        paraMap.put("userId", userId);
        paraMap.put("userAddressDefault",userAddressDefault.toString());
        Integer torf = this.baseMapper.addAddress(paraMap);
        if (CommonStatusEnum.SUCCESS.getCode() == torf) {
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult setDefault(Map<String, String> paraMap) {
        String token = paraMap.get("token");
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);

        Integer oneInteger =this.baseMapper.update(null,new LambdaUpdateWrapper<UserAddressEntity>()
                            .set(UserAddressEntity::getUserAddressDefault,0)
                            .eq(UserAddressEntity::getUserId,userId)
                            .eq(UserAddressEntity::getUserAddressDefault,1));
        Integer twoInteger = this.baseMapper.update(null,new LambdaUpdateWrapper<UserAddressEntity>()
                            .set(UserAddressEntity::getUserAddressDefault,1)
                            .eq(UserAddressEntity::getUserAddressId,paraMap.get("userAddressId").toString()));
        if ((oneInteger == 1 ||  oneInteger == 0) && twoInteger == 1) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);

    }
}
